/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-06-26     chenlei       the first version
 */
#include "motor_app.h"
#include "head.h"

struct rt_device_pwm *pwm_dev;
rt_uint32_t period = 50000;
//rt_uint32_t pulse = 50000;

int motor_pwm_init(void)
{
    //查找设备
    pwm_dev = (struct rt_device_pwm*)rt_device_find(PWM_DEV);
    if(pwm_dev == RT_NULL)
    {
        rt_kprintf("not find!");
        return RT_ERROR;
    }
    //设置PWM
    rt_pwm_set(pwm_dev,PWM_DEV_CHAN, period, 50000);
    //使能PWM
    rt_pwm_enable(pwm_dev, PWM_DEV_CHAN);
    return RT_EOK;
}

void motor_init(void)
{
    //PWM初始化
    motor_pwm_init();
    //引脚初始化
    rt_pin_mode(AIN1_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(AIN2_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(STYB_PIN, PIN_MODE_OUTPUT);

    rt_pin_write(AIN1_PIN, PIN_LOW);
    rt_pin_write(AIN2_PIN, PIN_LOW);
    rt_pin_write(STYB_PIN, PIN_LOW);

    motor_stop();
}

void motor_start(void)
{
    rt_pin_write(STYB_PIN, PIN_HIGH);
}

void motor_stop(void)
{
    rt_pin_write(STYB_PIN, PIN_LOW);
}

//正数地锁降下 负数地锁升起
void motor_set_pwm(int pwmvalue)
{
    motor_stop();

    if(pwmvalue >0)
    {
        rt_pin_write(AIN1_PIN, PIN_LOW);
        rt_pin_write(AIN2_PIN, PIN_HIGH);

        if(pwmvalue >100)
            pwmvalue = 100;
        if(pwmvalue < 1)
            pwmvalue = 1;
        pwmvalue = period * pwmvalue / 100;
        rt_pwm_set(pwm_dev,PWM_DEV_CHAN, period, pwmvalue);

    }
    else
    {
        rt_pin_write(AIN1_PIN, PIN_HIGH);
        rt_pin_write(AIN2_PIN, PIN_LOW);

        if(pwmvalue < -100)
            pwmvalue = -100;
        if(pwmvalue > -1)
            pwmvalue = -1;
        pwmvalue = period * pwmvalue / 100;
        rt_pwm_set(pwm_dev,PWM_DEV_CHAN, period, -pwmvalue);
    }

    motor_start();

}
